package pe.com.bbva.seguridad.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pe.com.bbva.seguridad.dao.ModuloDAO;
import pe.com.bbva.seguridad.domain.Modulo;
import pe.com.bbva.seguridad.domain.Usuario;
import pe.com.stefanini.core.dao.GenericDAOImpl;
import pe.com.stefanini.core.exceptions.BOException;
import pe.com.stefanini.core.exceptions.DAOException;

@Service("moduloDAO")
public class ModuloDAOImpl extends GenericDAOImpl<Modulo> implements ModuloDAO {

	private static String LISTAR_MODULOS_POR_USUARIO = 
			"SELECT A.* FROM (SELECT MO.* FROM TARGPS.TTARGPS_USUARIO US "
			+ "LEFT JOIN TARGPS.TTARGPS_USUARIO_PERFIL UP "
			+ "ON US.NID_USUARIO = UP.NID_USUARIO "
			+ "LEFT JOIN TARGPS.TTARGPS_PERFIL_MODULO PM "
			+ "ON PM.NID_PERFIL = UP.NID_PERFIL "
			+ "LEFT JOIN TARGPS.TTARGPS_MODULO MO "
			+ "ON MO.NID_MODULO = PM.NID_MODULO "
			+ "WHERE US.CODIGO_USUARIO = '%s' AND"
			+ " PM.NID_MODULO IS NOT NULL AND MO.ESTADO = '1' ) A "
			+ " START WITH A.SUPERIOR_ID IS NULL "
			+ " CONNECT BY PRIOR A.NID_MODULO = A.SUPERIOR_ID";

	@Autowired
	public ModuloDAOImpl(SessionFactory sessionFactory) {
		super(sessionFactory);
	}

	@SuppressWarnings("unchecked")
	public List<Modulo> findModulos(Modulo modulo) throws Exception, DAOException {
		String where = "";
		if (modulo.getDescripcion() == null) {
			modulo.setDescripcion("");
		}
		where = where + " upper(descripcion) like upper('%" + modulo.getDescripcion() + "%')";
		if (modulo.getCodigo() != null && !modulo.getCodigo().trim().equals("")) {
			where = where + " and upper(codigo) like upper('%" + modulo.getCodigo() + "%')";
		}
		if (modulo.getTipoModulo() != null && modulo.getTipoModulo().getId() != null) {
			where = where + " and tipoModulo.id =" + modulo.getTipoModulo().getId();
		}
		if(modulo.getEstado()!= null && !modulo.getEstado().equals("")){
			where = where +" and upper(estado) like upper('%" + modulo.getEstado()+ "%') ";
		}
		String orders = " order by fechaCreacion desc,codigo, tipoModulo.id, descripcion";
		if (where.length() > 0) {
			where = " where " + where;
		}
		List<Modulo> listaModulos = super.executeQuery(Modulo.class, where, orders);
		return listaModulos;
	}

	@SuppressWarnings("unchecked")
	public List<Modulo> findModulosByUsuario(Usuario usuario) throws BOException, DAOException {
		String query = String.format(LISTAR_MODULOS_POR_USUARIO, usuario.getCodigo());
		List<Modulo> listaModulo = super.executeSQL(query, Modulo.class);
		return listaModulo;
	}
}